<template>
 <div class="evaluation-trend">
    <div class="filter-container">
      <div class="filter-item">
        <label class="filter-label">开课学期：</label>
        <el-select 
          v-model="query.semester"
          placeholder="请选择开课学期"
          class="filter-select"
          @change="initCourse"
        >
          <el-option 
            v-for="semester in availableSemesters" 
            :key="semester" 
            :value="semester"
            :label="semester"
          />
        </el-select>
      </div>
      <div class="filter-item">
        <label class="filter-label">课程选择：</label>
        <el-select
        filterable
          v-model="query.subId"
          placeholder="请选择课程"
          class="filter-select"
          @change="fetchData"
        >
          <el-option
            v-for="(item, index) in courseList"
            :key="index"
            :label="item.courseName"
            :value="item.subId"
          />
        </el-select>
      </div>
    </div>
        <!-- 图表主体 -->
  <div class="chart-card">
      <div class="chart-container">
        <div 
          v-show="!loading && !error"
          ref="chartDom" 
          class="chart-main"
        ></div>

    <!-- 加载状态 -->
        <div v-show="loading" class="status-box">
          <el-icon class="loading-icon"><Loading /></el-icon>
          <span class="status-text">数据加载中...</span>
        </div>

        <!-- 错误状态 -->
        <div v-show="error" class="status-box error">
          <el-icon class="error-icon"><CircleCloseFilled /></el-icon>
          <span class="status-text">{{ errorMessage }}</span>
          <el-button 
            type="primary"
            size="small"
            @click="fetchData"
            class="retry-btn"
          >
            重试
          </el-button>
        </div>
      </div>
    </div>
  </div>
  </template>
  
  <script>
  import { getCourse,getTime} from '@/api/txyStudentEvaluation';
  import { getSemester1 } from '@/api/dashboard'
  import * as echarts from 'echarts'
  
  export default {
    data() {
      return {
        chartOption:{
          title: {
          text: '评分趋势变化图',
          left: 'center',
          textStyle: {
            fontSize: 18,
            color: '#333'
          }
        },
        tooltip: {
          trigger: 'axis',
          backgroundColor: 'rgba(255,255,255,0.95)',
          borderColor: '#ebeef5',
          borderWidth: 1,
          textStyle: {
            color: '#303133'
          },
          formatter: params => {
            const data = params[0]
            return `
              <div style="padding: 5px 10px;">
                <div style="margin: 5px 0;">日期：${this.formatDate(data.name)}</div>
                <div style="margin: 5px 0;">评分：${data.value} 分</div>
              </div>
            `
          }
        },
        xAxis: {
          type: 'category',
          boundaryGap: false,
          axisLabel: {
            rotate: 30,
            formatter: value => this.formatDate(value)
          }
        },
        yAxis: {
          type: 'value',
          axisLabel: {
            formatter: '{value} 分'
          }
        },
        series: [{
          type: 'line',
          smooth: true,
          symbol: 'circle',
          symbolSize: 8,
          itemStyle: {
            color: '#36a3eb'
          },
          areaStyle: {
            color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
              { offset: 0, color: 'rgba(54,163,235,0.6)' },
              { offset: 1, color: 'rgba(54,163,235,0.05)' }
            ])
          }
        }],
        dataZoom: [{
          type: 'slider',
          show: true,
          start: 0,
          end: 100,
          height: 20,
          bottom: 10
        }],
        grid: {
          top: 80,
          left: 60,
          right: 40,
          bottom: 100
        },
        },
        chartInstance: null,
        loading: true,
        error: false,
        errorMessage: '',
        availableSemesters: [], // 改为从后端动态获取
        rawData: [], // 原始数据
        query:{
          semester:'',
          subId:''
        },
        courseList:[],
      }
    },
    created(){
      getSemester1().then(res=>{
        this.availableSemesters=res.data
      })
    },
    methods:{
        // 获取后端数据
        initCourse(semester){
          getCourse(semester).then(res=>{
            this.courseList=res.data;
          })
        },
        async fetchData(){
            try {
              this.loading = true
              this.error = false
              
              // 替换为实际API地址
              const response = await getTime(this.query)
              const rawData = response.data

              if (!rawData || rawData.length === 0) {
                throw new Error('暂无数据')
              }

              this.processData(rawData)
              this.initChart()
            } catch (err) {
              this.error = true
              this.errorMessage = err.response 
                ? `请求失败：${err.response.data.message}` 
                : err.message
            } finally {
              this.loading = false
            }
        },

    // 处理数据
    processData(rawData) {
      // 1. 按日期排序
      const sortedData = [...rawData].sort((a, b) => 
        new Date(a.startDate) - new Date(b.startDate))
      
      // 2. 提取数据
      const xData = sortedData.map(item => item.startDate)
      const yData = sortedData.map(item => item.sumScore)

      // 3. 更新图表配置
      this.chartOption.xAxis.data = xData
      this.chartOption.series[0].data = yData
    },

    // 日期格式化
    formatDate(fullDate) {
      return fullDate.slice(0,10).replaceAll('-', '/')
    },

    // 初始化图表
    initChart() {
if (!this.chartInstance) {
    this.chartInstance = echarts.init(this.$refs.chartDom)
    // 添加窗口变化监听
    window.addEventListener('resize', () => {
        this.chartInstance.resize()
      })
    }
      // 每次更新时清空旧配置
      this.chartInstance.clear() 
      this.chartInstance.setOption(this.chartOption)
      // 强制触发resize
      setTimeout(() => {
        this.chartInstance.resize()
      }, 100)
      },

    // 窗口变化自适应
    handleResize() {
      this.chartInstance?.resize()
    }
        
    },
    mounted(){
      window.addEventListener('resize', this.handleResize)
    },
    beforeDestroy() {
    window.removeEventListener('resize', this.handleResize)
    this.chartInstance?.dispose()
    }
  }
  </script>

<style scoped lang="scss">
.evaluation-trend {
  padding: 24px;
  background: #f5f7fa;
  min-height: 100vh;
}

.filter-container {
  display: flex;
  gap: 20px;
  margin-bottom: 24px;
  flex-wrap: wrap;
}

.filter-item {
  display: flex;
  align-items: center;
  background: white;
  padding: 12px 20px;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0,0,0,0.05);
  transition: box-shadow 0.3s;

  &:hover {
    box-shadow: 0 4px 12px rgba(0,0,0,0.1);
  }
}

.filter-label {
  font-size: 14px;
  color: #606266;
  margin-right: 12px;
  white-space: nowrap;
}

.filter-select {
  width: 280px;
}

.chart-card {
  background: white;
  border-radius: 12px;
  box-shadow: 0 4px 12px rgba(0,0,0,0.08);
  overflow: hidden;
}

.chart-container {
  padding: 24px;
  position: relative;
  min-height: 600px;
}

.chart-main {
  width: 100%;
  height: 600px;
}

.status-box {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 12px;
  color: #909399;

  .loading-icon {
    font-size: 48px;
    color: #409eff;
    animation: rotating 2s linear infinite;
  }

  .error-icon {
    font-size: 48px;
    color: #f56c6c;
  }

  .status-text {
    font-size: 16px;
    font-weight: 500;
  }

  &.error {
    color: #f56c6c;
  }
}

.retry-btn {
  margin-top: 8px;
}

@keyframes rotating {
  from { transform: rotate(0deg); }
  to { transform: rotate(360deg); }
}

@media (max-width: 768px) {
  .filter-item {
    width: 100%;
    
    .filter-select {
      width: 100%;
    }
  }
  
  .chart-main {
    height: 400px;
  }
}
</style>